package com.jnc.core.config.shiro.filter;

import com.jnc.common.constant.ShiroConstant;
import com.jnc.common.util.convert.SerializeUtil;
import com.jnc.core.config.redis.RedisStore;
import com.jnc.core.config.shiro.util.ShiroUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.PathMatchingFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @Author: jjn
 * @Date: 2018/11/2
 * @Desc: 同步session到Redis 需要放到Shiro过滤器之前
 */
public class SyncSessionFilter extends PathMatchingFilter {

    private RedisStore redisStore;

    public SyncSessionFilter(RedisStore redisStore) {
        this.redisStore = redisStore;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        //获取请求的SessionId和Session
        Session session = ShiroUtil.getSession();
        String sessionId = ShiroUtil.getSessionId();
        byte[] key = (ShiroConstant.SHIRO_SESSION_PREFIX + sessionId).getBytes();
        //判断key是否存在
        boolean check = redisStore.exists(key);
        if(!check){
            //当不存在，则同步到Redis
            redisStore.setExpire(key, SerializeUtil.serialize(session), ShiroConstant.EXPIRE_SECONDS);
        }
        return true;
    }
}
